import os
import pandas as pd
import shutil
import config
from PIL import Image

from pylab import mpl

# 设置显示中文字体
mpl.rcParams["font.sans-serif"] = ["SimHei"]
# 设置正常显示符号
mpl.rcParams["axes.unicode_minus"] = False

device = config.device
transform = config.transform
app_config = config.get_app_config()
train_path = app_config.train_path
test_path = app_config.test_path
train_class_csv_path = app_config.train_class_csv_path
test_class_csv_path = app_config.test_class_csv_path
test_csv_path = app_config.test_csv_path
features_file_path = app_config.features_file_path
model_file_path = app_config.model_file_path
num_epochs = app_config.num_epochs
lr = app_config.lr
momentum = app_config.momentum
batch_size = app_config.batch_size


def config_class_dir():
    os.listdir(train_path)
    train_class_data = pd.read_csv(config.train_class_csv_path)

    for index, row in train_class_data.iterrows():
        old_file_path = os.path.join(train_path, row['name'])
        class_path = os.path.join(train_path, str(row['class']))
        new_path = os.path.join(class_path, f"{row['name']}")

        if os.path.exists(old_file_path):
            if not os.path.exists(class_path):
                os.mkdir(class_path)
            shutil.move(old_file_path, new_path)

    test_class_csv_path = pd.read_csv(config.test_class_csv_path)
    for index, row in test_class_csv_path.iterrows():
        old_file_path = os.path.join(test_path, row['name'])
        class_path = os.path.join(test_path, str(row['class']))
        new_path = os.path.join(class_path, f"{row['Usage']}_{row['name']}")

        if os.path.exists(old_file_path):
            if not os.path.exists(class_path):
                os.mkdir(class_path)
            shutil.move(old_file_path, new_path)


def count_files_in_directory(path):
    file_count = 0
    sizes = {}
    for root, dirs, files in os.walk(path):
        for filename in files:
            image_path = os.path.join(root, filename)
            img = Image.open(image_path)
            width, height = img.size
            sizes[filename] = (width, height)
        file_count += len(files)
    return file_count, sizes

def get_stats_for_subdirectories(path):
    dir_stats = {}
    file_sizes = {}
    # root 表示当前正在访问的文件夹路径
    # dirs 表示该文件夹下的子目录名list
    # files 表示该文件夹下的文件list
    for root, dirs, files in os.walk(path):
        for d in dirs:
            subdir_path = os.path.join(root, d)
            file_count, sizes = count_files_in_directory(subdir_path)
            dir_stats[d] = file_count
            file_sizes.update(sizes)
    max_files = max(dir_stats.values())
    min_files = min(dir_stats.values())
    avg_files = sum(dir_stats.values()) / len(dir_stats)

    print(len(dir_stats))
    print(len(file_sizes))

    max_width = float('-inf')  # 初始化为负无穷大
    min_width = float('+inf')  # 初始化为正无穷大
    total_width = 0.0  # 记录总和

    max_height = float('-inf')  # 初始化为负无穷大
    min_height = float('+inf')  # 初始化为正无穷大
    total_height = 0.0
    count = len(file_sizes)  # 记录元组的数量

    for value in file_sizes.values():
        width_element = value[0]  # 获取元组的第一个元素
        height_element = value[1]  # 获取元组的第一个元素

        if width_element > max_width:
            max_width = width_element
        if width_element < min_width:
            min_width = width_element
        total_width += width_element

        if height_element > max_height:
            max_height = height_element
        if height_element < min_height:
            min_height = height_element
        total_height += height_element

    average_width = total_width / count  # 求平均值
    average_height = total_height / count  # 求平均值

    print("最大高度:", max_height)
    print("最小高度:", min_height)
    print("平均高度:", average_height)
    print("最大宽度:", max_width)
    print("最小宽度:", min_width)
    print("平均宽度:", average_width)
    print("最大文件数:", max_files)
    print("最小文件数:", min_files)
    print("平均文件数:", avg_files)


if __name__ == '__main__':
    # config_class_dir()

    # 最大高度: 4032
    # 最小高度: 130
    # 平均高度: 1068
    # 最大宽度: 4032
    # 最小宽度: 130
    # 平均宽度: 844
    # 最大文件数: 71
    # 最小文件数: 2
    # 平均文件数: 8
    print("hellow world")
    # 每个分类最多71个图片，最少2个图片，平均8个图片；
    get_stats_for_subdirectories(train_path)

